package com.example.administrator.ygddriver.into.login;

import android.content.Intent;
import android.os.CountDownTimer;
import android.os.Handler;
import android.support.v7.widget.CardView;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.example.administrator.ygddriver.R;
import com.example.administrator.ygddriver.base.BaseActivity;
import com.example.administrator.ygddriver.base.BaseBean;
import com.example.administrator.ygddriver.base.BaseHint;
import com.example.administrator.ygddriver.base.UserBean;
import com.example.administrator.ygddriver.into.login.driverjoin.DriverJoinActivity;
import com.example.administrator.ygddriver.liteorm.LiteOrmTools;
import com.example.administrator.ygddriver.liteorm.SingleLiteOrm;
import com.example.administrator.ygddriver.netty.TcpClient;
import com.example.administrator.ygddriver.tool.IsPhoneNum;
import com.example.administrator.ygddriver.tool.OkGoRequests;
import com.example.administrator.ygddriver.tool.SimpleToolbar;
import com.example.administrator.ygddriver.tool.UrlValuse;

import java.util.HashMap;
import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

import static com.litesuits.orm.db.impl.CascadeSQLiteImpl.TAG;

/**
 * 注册界面
 */
public class LogInActivity extends BaseActivity implements View.OnClickListener {
    private SimpleToolbar simpleToolbar;
    private ImageView mEyesIv, mAccountDelIv, mPasswordDelIv;
    private EditText mAccountEt, mPasswordEt, mCodeEt, mBranchEt;
    private RelativeLayout mNextRl;
    private boolean isExit = false;
    private CountDownTimer timer;
    private Button mVerificationBtn;

    @Override
    public int initLayout() {
        return R.layout.activity_log_in;
    }

    @Override
    public void initView() {
        simpleToolbar = findViewById(R.id.activity_log_in_stb);
        mEyesIv = findViewById(R.id.activity_log_in_eyes_iv);
        mAccountDelIv = findViewById(R.id.activity_log_in_account_del_iv);
        mPasswordDelIv = findViewById(R.id.activity_log_in_password_del_iv);
        mAccountEt = findViewById(R.id.activity_log_in_account_et);
        mPasswordEt = findViewById(R.id.activity_log_in_password_et);
        mCodeEt = findViewById(R.id.activity_log_in_verification_et);
        mNextRl = findViewById(R.id.activity_log_in_cv_next);
        mBranchEt = findViewById(R.id.activity_log_in_verification_branch_et);
        mVerificationBtn = findViewById(R.id.activity_log_in_get_verification_btn);
        mVerificationBtn.setOnClickListener(this);
        mNextRl.setOnClickListener(this);
        mEyesIv.setOnClickListener(this);
        mPasswordDelIv.setOnClickListener(this);
        mAccountDelIv.setOnClickListener(this);
    }

    @Override
    public void initDate() {
        setSimpleToolbar();
        addEt();
    }

    private void setSimpleToolbar() {
        simpleToolbar.setMainTitle("注册");
        simpleToolbar.setMainTitleColor("#000000");
        simpleToolbar.setBackIv(R.mipmap.left_title);
        simpleToolbar.setToolColor("#ffffff");
        simpleToolbar.setBackIvClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.activity_log_in_eyes_iv:
                mPasswordEt.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                break;
            case R.id.activity_log_in_account_del_iv:
                mAccountEt.setText("");
                break;
            case R.id.activity_log_in_password_del_iv:
                mPasswordEt.setText("");
                break;
            case R.id.activity_log_in_cv_next:
                if (judge(mAccountEt.getText().toString(), mPasswordEt.getText().toString(), mCodeEt.getText().toString())) {
                    initRegisterHtml(mAccountEt.getText().toString(), mPasswordEt.getText().toString(), mCodeEt.getText().toString(), mBranchEt.getText().toString());
                }
                break;
            case R.id.activity_log_in_get_verification_btn:
                startTime();
                if (IsPhoneNum.isPhoneNumber(String.valueOf(mAccountEt.getText()))) {
                    HashMap<String, String> params = new HashMap<>();
                    params.put("c_phone", String.valueOf(mAccountEt.getText()));
                    params.put("type", "2");
                    initGetVerificationHtml(params);
                } else {
                    timer.cancel();
                    BaseHint baseHint = new BaseHint.addHint().setParameter(LogInActivity.this, "提示", "请输入正确电话号码");
                    baseHint.show();
                }
                break;

        }
    }

    private Boolean judge(String account, String password, String code) {
        if (!IsPhoneNum.isPhoneNumber(account)) {
            BaseHint baseHint = new BaseHint.addHint().setParameter(LogInActivity.this, "提示", "请输入正确的手机账号");
            baseHint.show();
            return false;
        }
        if (!TextUtils.isEmpty(password) && password.length() < 6 && TextUtils.isEmpty(code)) {
            BaseHint baseHint = new BaseHint.addHint().setParameter(LogInActivity.this, "提示", "密码长度错误");
            baseHint.show();
            return false;
        }
        if (!TextUtils.isEmpty(code) && code.length() < 6) {
            BaseHint baseHint = new BaseHint.addHint().setParameter(LogInActivity.this, "提示", "验证码错误");
            baseHint.show();
            return false;
        }

        return true;
    }

    private void addEt() {
        mAccountEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                mAccountDelIv.setVisibility(View.VISIBLE);
                if (TextUtils.isEmpty(mAccountEt.getText())) {
                    mAccountDelIv.setVisibility(View.GONE);
                } else {
                    mAccountDelIv.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        mAccountEt.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    if (TextUtils.isEmpty(mAccountEt.getText())) {
                        mAccountDelIv.setVisibility(View.GONE);
                    } else {
                        mAccountDelIv.setVisibility(View.VISIBLE);
                    }
                } else {
                    mAccountDelIv.setVisibility(View.GONE);
                }
            }
        });
        mPasswordEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                mPasswordDelIv.setVisibility(View.VISIBLE);
                mEyesIv.setVisibility(View.VISIBLE);
                if (TextUtils.isEmpty(mPasswordEt.getText())) {
                    mPasswordDelIv.setVisibility(View.GONE);
                    mEyesIv.setVisibility(View.GONE);
                } else {
                    mPasswordDelIv.setVisibility(View.VISIBLE);
                    mEyesIv.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        mPasswordEt.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    if (TextUtils.isEmpty(mPasswordEt.getText())) {
                        mPasswordDelIv.setVisibility(View.GONE);
                        mEyesIv.setVisibility(View.GONE);
                    } else {
                        mPasswordDelIv.setVisibility(View.VISIBLE);
                        mEyesIv.setVisibility(View.VISIBLE);
                    }
                } else {
                    mPasswordDelIv.setVisibility(View.GONE);
                    mEyesIv.setVisibility(View.GONE);
                }
            }
        });

    }

    //注册
    private void initRegisterHtml(String c_account, String c_password, String c_code, String c_worknumber) {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("c_account", c_account);
        hashMap.put("c_password", c_password);
        hashMap.put("c_type", "2");
        hashMap.put("c_code", c_code);
        hashMap.put("c_worknumber", c_worknumber);
        hashMap.put("c_registrationid",JPushInterface.getRegistrationID(this));
        OkGoRequests.getInstance().putRequestAsync(UrlValuse.POST_API_BASE + UrlValuse.REGISTER, hashMap, LogInRegisterRequestBean.class, new OkGoRequests.OnTrue<LogInRegisterRequestBean>() {
            @Override
            public void hasData(final LogInRegisterRequestBean date) {
                if (date.isSuccess()) {
                    LiteOrmTools.getInformation(UserBean.class, LogInActivity.this, new LiteOrmTools.On<UserBean>() {
                        @Override
                        public void hasData(UserBean data) {
                            data.setC_account(date.getResult().getC_account());
                            data.setC_id(date.getResult().getC_id());
                            data.setC_token(date.getResult().getC_token());
                            SingleLiteOrm.getSingleLiteOrm(LogInActivity.this).SingleLite().update(data);
                        }
                    }, new LiteOrmTools.OFF() {
                        @Override
                        public void noData() {
                            UserBean data = new UserBean();
                            data.setC_account(date.getResult().getC_account());
                            data.setC_id(date.getResult().getC_id());
                            data.setC_token(date.getResult().getC_token());
                            SingleLiteOrm.getSingleLiteOrm(LogInActivity.this).SingleLite().insert(data);
                        }
                    });
                    Intent intent = new Intent(LogInActivity.this, DriverJoinActivity.class);
                    startActivity(intent);
                } else {
                    BaseHint baseHint = new BaseHint.addHint().setParameter(LogInActivity.this, "提示", date.getLocalizedMessage());
                    baseHint.show();
                }
            }
        }, new OkGoRequests.OnError<LogInRegisterRequestBean>() {
            @Override
            public void noData() {

            }
        });

    }

    //获取验证码
    private void initGetVerificationHtml(HashMap<String, String> params) {
        OkGoRequests.getInstance().putRequestAsync(UrlValuse.POST_API_BASE + UrlValuse.CREATE_VERIFICATION_CODE, params, BaseBean.class, new OkGoRequests.OnTrue<BaseBean>() {
            @Override
            public void hasData(BaseBean data) {
                if (data.isSuccess()) {

                } else {
                    timer.cancel();
                    mVerificationBtn.setClickable(true);
                    mVerificationBtn.setText("获取验证码");
                    BaseHint baseHint = new BaseHint.addHint().setParameter(LogInActivity.this, "提示", data.getLocalizedMessage());
                    baseHint.show();
                }

            }
        }, new OkGoRequests.OnError<BaseBean>() {
            @Override
            public void noData() {

            }
        });


    }

    private void startTime() {
        timer = new CountDownTimer(60000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                mVerificationBtn.setClickable(false);
                mVerificationBtn.setText((millisUntilFinished / 1000) + "秒");
            }

            @Override
            public void onFinish() {
                mVerificationBtn.setClickable(true);
                mVerificationBtn.setText("获取验证码");
            }
        }.start();


    }


}
